//
//  WJImageAutoSizeDemo1Controller.m
//  JerryIos
//
//  Created by 王军 on 2018/2/14.
//  Copyright © 2018年 王军. All rights reserved.
//

#import "WJIASDemo1Controller.h"
#import "WJIASDemo1Cell.h"
#import "XHWebImageAutoSize.h"
#import "WJIASData1.h"
#import "MJExtension.h"

@interface WJIASDemo1Controller ()

@property(nonatomic,strong) NSArray *itemArray;

@end

static NSString *const cellId = @"WJIASDemo1Cell";

@implementation WJIASDemo1Controller

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //取消系统自带的分隔线。
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    [self.tableView registerNib:[UINib nibWithNibName:cellId bundle:nil] forCellReuseIdentifier:cellId];

    
}

-(NSArray *)itemArray {
    if (_itemArray == nil) {
        NSString *json = [NSString stringWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"image01" ofType:@"json"]
                                                   encoding:NSUTF8StringEncoding
                                                      error:nil];
        WJIASData1 *iasData = [WJIASData1 mj_objectWithKeyValues:json];
        _itemArray = iasData.data;
    }
    return _itemArray;
}

#pragma mark - Table view data source
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.itemArray.count;
}

-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *imgUrl = self.itemArray[indexPath.row];
    
    /**
     *  参数1:图片URL
     *  参数2:imageView 宽度
     *  参数3:预估高度,(此高度仅在图片尚未加载出来前起作用,不影响真实高度)
     */
    return [XHWebImageAutoSize imageHeightForURL:[NSURL URLWithString:imgUrl]
                                     layoutWidth:[UIScreen mainScreen].bounds.size.width-16
                                  estimateHeight:200];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    WJIASDemo1Cell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if(!cell){
        cell = [[WJIASDemo1Cell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
    }
    
    NSString *imgUrl = self.itemArray[indexPath.row];
    [cell.imgView sd_setImageWithURL:[NSURL URLWithString:imgUrl] completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        /** 缓存image size */
        [XHWebImageAutoSize storeImageSize:image forURL:imageURL completed:^(BOOL result) {
            /** reload  */
            if(result)  [tableView  xh_reloadDataForURL:imageURL];
        }];
    }];
    return cell;
    
}


@end
